import React, { useCallback } from 'react';
import { Button, Form, Card, message, Spin, Input, Table, Switch, InputNumber } from 'antd';
import {
  globalConfigV1AdminControllerShow,
  globalConfigV1AdminControllerUpdate,
} from '@/services/auto/globalConfigAdmin';
import { useRequest } from 'ahooks';
import { DragHandle, SortableBody, SortableItem } from "@/components/Drag";
import { SortEnd } from "react-sortable-hoc";
import { arrayMoveImmutable } from "array-move";
import { useModel } from "@umijs/max";
import EvaluationSelect from '@/components/EvaluationSelect';
import { EvaluationCategory } from 'common/utils/data';

export default function GlobalConfig() {
  const {runAsync: globalConfigDataRunAsync} = useModel('global-config');

  const [form] = Form.useForm<FormData>();

  const { loading: getGlobalConfigUniqueLoading } = useRequest(
    globalConfigV1AdminControllerShow,
    {
      onSuccess: res => {
        form.setFieldsValue({
          targets: res.targets.map(item=>{
            return {
              ...item,
              id: Math.random(),
            }
          }),
          sensitive: res.sensitive,
          presetSegmentFreq: res.presetSegmentFreq.map(item=>{
            const {evaluationUuid, dataGroup, ...restItem} = item;
            return {
              ...restItem,
              evaluation: {
                evaluationUuid,
                dataGroup,
              },
              id: Math.random(),
            } as any
          }),
        });
      },
    },
  );

  const {
    runAsync: patchGlobalConfigRun,
    loading: patchGlobalConfigLoading,
  } = useRequest(globalConfigV1AdminControllerUpdate, {
    manual: true,
    onSuccess: () => {
      globalConfigDataRunAsync();
      message.success('保存成功');
    },
  });

  const getBody = useCallback((props: any) => (
    <SortableBody
      useDragHandle
      disableAutoscroll
      helperClass="row-dragging"
      onSortEnd={({ oldIndex, newIndex }: SortEnd) => {
        if (oldIndex !== newIndex) {
          const newData = arrayMoveImmutable(form.getFieldsValue().targets?.slice(), oldIndex, newIndex).filter(
            el => !!el,
          );
          form.setFieldsValue({
            targets: newData,
          })
        }
      }}
      {...props}
    />
  ),[])

  const getRow = useCallback((props: any) => {
    const index = form.getFieldsValue().targets?.findIndex(x => x.id === props['data-row-key']);
    return <SortableItem index={index} {...props} />;
  },[])

  return (
    <>
      <Card bordered={false} style={{ width: '100%' }}>
        <Spin spinning={getGlobalConfigUniqueLoading}>
          <Form
            style={{ width: '100%' }}
            layout="vertical"
            form={form}
            onFinish={values => {
              patchGlobalConfigRun({
                targets: values.targets.map(item=>{
                  const {id,...restItem} = item;
                  return restItem
                }),
                presetSegmentFreq: values.presetSegmentFreq.map(item=>{
                  const {id,evaluation,...restItem} = item;
                  return {
                    ...restItem,
                    evaluationUuid: evaluation?.evaluationUuid,
                    dataGroup: evaluation?.dataGroup,
                  }
                }),
                sensitive: values.sensitive,
              });
            }}
            onFinishFailed={({ errorFields }) => {
              form.scrollToField(errorFields[0].name, {
                behavior: 'smooth',
                block: 'center',
              });
              message.warning('表单格式有误请检查');
            }}
          >
            <Form.Item
              name="presetSegmentFreq"
              label="预设分段"
              rules={[
                {
                  required: true,
                  message: '请输入',
                },
              ]}
              valuePropName="dataSource"
            >
              <Table
                scroll={{x: 'max-content'}}
                pagination={false}
                footer={()=>{
                return <Button block onClick={()=>{
                  form.setFieldsValue({
                    presetSegmentFreq: form.getFieldsValue().presetSegmentFreq.concat({
                      id: Math.random(),
                    })
                  })
                }}>增加一行</Button>
              }}
                components={{
                  body: {
                    wrapper: getBody,
                    row: getRow,
                  },
                }}
                rowKey="id" columns={[
                {
                  title: '名称',
                  key: 'name',
                  width: 150,
                  render: (_,record,index)=>{
                    return <>
                      <Form.Item name={['presetSegmentFreq', index ,'id']} noStyle hidden>
                        <Input />
                      </Form.Item>
                      <Form.Item name={['presetSegmentFreq', index ,'name']}>
                        <Input maxLength={200} />
                      </Form.Item>
                    </>
                  }
                },
                {
                  title: '开始频率',
                  key: 'start',
                  width: 100,
                  render: (_,record,index)=>{
                    return <>
                      <Form.Item name={['presetSegmentFreq', index ,'start']}>
                        <InputNumber
                          min={20}
                          max={20000}
                        />
                      </Form.Item>
                    </>
                  }
                },
                {
                  title: '结束频率',
                  key: 'end',
                  width: 100,
                  render: (_,record,index)=>{
                    return <>
                      <Form.Item name={['presetSegmentFreq', index ,'end']}>
                        <InputNumber
                          min={20}
                          max={20000}
                        />
                      </Form.Item>
                    </>
                  }
                },
                {
                  title: '耳机',
                  key: 'evaluation',
                  width: 200,
                  render: (_,record,index)=>{
                    return <>
                      <Form.Item name={['presetSegmentFreq', index ,'evaluation']}>
                        <EvaluationSelect category={EvaluationCategory.EARBUDS} withDataGroup />
                      </Form.Item>
                    </>
                  }
                },
                {
                  title: '操作',
                  key: 'option',
                  width: 60,
                  render: (_,record)=>{
                    return <>
                     <Button onClick={() => {
                        form.setFieldsValue({
                          presetSegmentFreq: form.getFieldsValue().presetSegmentFreq.filter(item => {
                            return item.id !== record.id;
                          })
                        })
                      }}>删除</Button>
                    </>
                  }
                },
              ]} />
            </Form.Item>
            <Form.Item
              name="targets"
              label="target"
              rules={[
                {
                  required: true,
                  message: '请输入',
                },
              ]}
              valuePropName="dataSource"
            >
              <Table
                pagination={false}
                footer={()=>{
                return <Button block onClick={()=>{
                  form.setFieldsValue({
                    targets: form.getFieldsValue().targets.concat({
                      id: Math.random(),
                      name: '',
                      data: '',
                      default: false,
                    })
                  })
                }}>增加一行</Button>
              }}
                components={{
                  body: {
                    wrapper: getBody,
                    row: getRow,
                  },
                }}
                rowKey="id" columns={[
                {
                  title: '排序',
                  key: 'sort',
                  width: 60,
                  render: () => <DragHandle />,
                  className: 'drag-visible',
                },
                {
                  title: '名称',
                  key: 'name',
                  render: (_,record,index)=>{
                    return <>
                      <Form.Item name={['targets', index ,'id']} noStyle hidden>
                        <Input />
                      </Form.Item>
                      <Form.Item name={['targets', index ,'name']}>
                        <Input maxLength={200} />
                      </Form.Item>
                    </>
                  }
                },
                {
                  title: 'target数据（不要有逗号,）',
                  key: 'data',
                  render: (_,record,index)=>{
                    return <>
                      <Form.Item name={['targets', index ,'data']}>
                        <Input.TextArea
                          autoSize={{
                            minRows: 5,
                            maxRows: 10,
                          }}
                        />
                      </Form.Item>
                    </>
                  }
                },
                {
                  title: '是否默认',
                  key: 'default',
                  render: (_,record,index)=>{
                    return <>
                      <Form.Item name={['targets', index ,'default']} valuePropName="checked">
                        <Switch disabled={record.default} onChange={()=>{
                          form.setFieldsValue({
                            targets: form.getFieldsValue().targets.map((it)=>{
                              return {
                                ...it,
                                default: it.id === record.id,
                              }
                            })
                          })
                        }} />
                      </Form.Item>
                    </>
                  }
                },
                {
                  title: '操作',
                  key: 'option',
                  render: (_,record)=>{
                    return <>
                      {!record.default && <Button onClick={() => {
                        form.setFieldsValue({
                          targets: form.getFieldsValue().targets.filter(item => {
                            return item.id !== record.id;
                          })
                        })
                      }}>删除</Button>}
                    </>
                  }
                },
              ]} />
            </Form.Item>
            <Form.Item
              name="sensitive"
              label="敏感词（回车分隔）"
            >
              <Input.TextArea
                autoSize={{
                  minRows: 5,
                  maxRows: 20,
                }}
              />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 7, span: 10 }}>
              <Button
                block
                type="primary"
                htmlType="submit"
                loading={patchGlobalConfigLoading}
              >
                确认
              </Button>
            </Form.Item>
          </Form>
        </Spin>
      </Card>
    </>
  );
};

interface FormData extends Omit<API.GlobalConfigAdminUpdateDto , 'targets' | 'presetSegmentFreq'>{
  targets: (Exclude<API.GlobalConfigAdminUpdateDto['targets'], undefined>[number] & {id: number})[];
  presetSegmentFreq: (Partial<Omit<Exclude<API.GlobalConfigAdminUpdateDto['presetSegmentFreq'], undefined>[number], 'evaluationUuid' | 'dataGroup'>> & {
    id: number,
    evaluation?: {
      evaluationUuid?: string;
      dataGroup?: string;
    },
  })[];
}
